export function parseListToMarkdown(blocks) {
  let items = {};
  switch (blocks.style) {
    case 'unordered':
    case 'ordered':
      items = generateMarkdownList(blocks.items, blocks.style);

      return items;
    default:
      break;
  }
}

function generateMarkdownList(data, flag) {
  let markdownList = '';

  data.forEach((item, i) => {
    const dot = flag === 'unordered' ? '-' : i + 1 + '.';
    markdownList += `${dot} ${item.content}\n`;
    if (item.items.length > 0) {
      item.items.forEach((subItem, m) => {
        const dot = flag === 'unordered' ? '-' : m + 1 + '.';
        markdownList += `  ${dot} ${subItem.content}\n`;
      });
    }
  });
  return markdownList;
}

const convertToEditorJSFormat = (input)=> {
  const convertItem = (item) => {
    let content = ''
    let items;

    for (const child of item.children) {
      if ('type' in child && child.type === 'paragraph') {
        content = child.children.map(textNode => {
          if ('value' in textNode) {
            return textNode.value
          } else if ('children' in textNode && textNode.children.length > 0) {
            return textNode.children[0].value
          }
          return ''
        }).join('')
      } else if ('type' in child && child.type === 'list') {
        items = child.children.map(convertItem)
      }
    }

    return { content, ...(items && items.length > 0 ? { items } : {}) }
  }

  return {
    items: input.children.map(convertItem)
  }
}

export function parseMarkdownToList(blocks) {
  let listData = {};
  // const itemData = [];

  // blocks.children.forEach((items) => {
  //   items.children.forEach((listItem) => {
  //     listItem.children.forEach((listEntry) => {
  //       itemData.push({content: listEntry.value});
  //     });
  //   });
  // });
  const { items } = convertToEditorJSFormat(blocks);

  listData = {
    data: {
      items,
      style: blocks.ordered ? 'ordered' : 'unordered',
    },
    type: 'list',
  };

  return listData;
}
